//
//  CameraViewController.m
//  project
//
//  Created by 圆圆陈 on 2017/12/18.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "CameraViewController.h"
#import "ShowImagesController.h"
#import "CustomTabBar.h"
#define CAMERA_TOPVIEW_HEIGHT                  44 //title
//对焦
#define ADJUSTINT_FOCUS                        @"adjustingFocus"
#define LOW_ALPHA                              0.7f
#define HIGH_ALPHA                             1.0f
#define SWITCH_SHOW_FOCUSVIEW_UNTIL_FOCUS_DONE 0        //对焦框是否一直闪到对焦完成
@interface CameraViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) SCCaptureSessionManager *captureManager;

@property (nonatomic, strong) UIButton *cancelBtn;      // 取消拍照返回
@property (nonatomic, strong) UIButton *takePictureBtn; // 拍照
@property (nonatomic, strong) UIButton *flashLightBtn;  // 打开闪光等
@property (nonatomic, strong) UIButton *cameraTypeBtn;  // 选择照相机,前后摄像头
@property (nonatomic, strong) UIButton *takedImage;  // 已经拍到的照片
@property (nonatomic, strong) UIButton *testButton;
@property (nonatomic, strong) UIButton *testButton2;
@property (nonatomic, strong) UILabel  *testLabel;

@property (nonatomic, strong) UIImage  *image;
@property (nonatomic, strong) NSString *albumName;

@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, assign) BOOL           isEnable;
@property (nonatomic, strong) UIImage        *takeImageLast;
//对焦
@property (nonatomic, strong) UIImageView *focusImageView;
@end

@implementation CameraViewController {
    int     alphaTimes;
    CGPoint currTouchPoint;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self createGroupSelf];
    [SN_PublicClass setBLTControlTDelegate:self];
    [self performSelector:@selector(setPhotoControl) withObject:nil afterDelay:0.2];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [SN_PublicClass setBLTControlTDelegate:[CustomTabBar new]];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"updateBleState" object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"updateBleState" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadCameraView];
    [self loadUpButtons];
    [self loadDownButtons];
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus != AVAuthorizationStatusRestricted && authStatus != AVAuthorizationStatusDenied) {
        //已有权限
        [self addFocusView];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBleConectState) name:@"updateBleState" object:nil];
    
    NSString *mediaType = AVMediaTypeVideo;
    
    AVAuthorizationStatus MediaType = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if (MediaType == ALAuthorizationStatusRestricted || MediaType == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"相机")
                                                        message:SN_Text(@"是否打开相机") delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:SN_Text(@"取消"), SN_Text(@"确定"), nil];
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        alert.tag = 101;
        [alert show];
        return;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if (alertView.tag == 101) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    }
}

- (void)updateBleConectState {
    if (KK_BLEConnect.isConnected && !KK_BLEConnect.isUpdateing) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setPhotoControl) object:nil];
        [self performSelector:@selector(setPhotoControl) withObject:nil afterDelay:3.0];
    }
}

- (void)setPhotoControl {
    NSLog(@"intoPhoto");
    [KK_BLESend sendControlTakePhotoState:YES WithUpdateBlock:^(id object, KKBLEAcceptType type) {
    }];
}

- (void)bltControlTakePhoto {
    SHOWMBProgressHUD(HHH_Text(@"拍照"), nil, nil, NO, 1);
    NSLog(@"isenable == %d", _isEnable);
    if (_isEnable) {
        [_captureManager takePicture:^(UIImage *stillImage)
         {
             _isEnable = NO;
             dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                 [self saveImageToPhotoAlbum:stillImage]; //存至本机
             });
             [_takedImage setBackgroundImage:stillImage forState:UIControlStateNormal];
         }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 加载相机
- (void)loadCameraView {
    SCCaptureSessionManager *manager = [[SCCaptureSessionManager alloc] init];
    
    //AvcaptureManager
    if (CGRectEqualToRect(_previewRect, CGRectZero)) {
        self.previewRect = self.view.bounds;
    }
    
    [manager configureWithParentLayer:self.view previewRect:_previewRect];
    self.captureManager = manager;
    
    [_captureManager.session startRunning];
    _isEnable = YES;
}

//对焦的框
- (void)addFocusView {
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"touch_focus_x.png"]];
    
    imgView.alpha = 0;
    [self.view addSubview:imgView];
    self.focusImageView = imgView;
    
#if SWITCH_SHOW_FOCUSVIEW_UNTIL_FOCUS_DONE
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device && [device isFocusPointOfInterestSupported]) {
        [device addObserver:self forKeyPath:ADJUSTINT_FOCUS options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
#endif
    
    
    [_captureManager focusInPoint:self.view.center];
    
    //对焦框
    [_focusImageView setCenter:self.view.center];
    
    _focusImageView.transform = CGAffineTransformMakeScale(2.0, 2.0);
    
#if SWITCH_SHOW_FOCUSVIEW_UNTIL_FOCUS_DONE  //对焦框是否一直闪到对焦完成
    [UIView animateWithDuration:0.1f animations:^{
        _focusImageView.alpha = HIGH_ALPHA;
        _focusImageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
        [self showFocusInPoint:self.view.center];
    }];
#else
    [UIView animateWithDuration:0.3f delay:0.f options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _focusImageView.alpha = 1.f;
        _focusImageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5f delay:0.5f options:UIViewAnimationOptionAllowUserInteraction animations:^{
            _focusImageView.alpha = 0.f;
        } completion:nil];
    }];
#endif
}

// 加载相机上端的按钮
- (void)loadUpButtons {
    self.flashLightBtn    = [UIButton buttonWithType:UIButtonTypeCustom];
    _flashLightBtn.frame  = CGRectMake(0, 0, 40, 60);
    _flashLightBtn.center = CGPointMake(50, 60);
    [_flashLightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_flashLightBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_flashLightBtn setImage:[UIImage imageNamed:@"flashing_off"] forState:UIControlStateNormal];
    [self.view addSubview:_flashLightBtn];
    
    self.cameraTypeBtn    = [UIButton buttonWithType:UIButtonTypeCustom];
    _cameraTypeBtn.frame  = CGRectMake(0, 0, 60, 60);
    _cameraTypeBtn.center = CGPointMake(self.view.width - 38, 84);
    [_cameraTypeBtn setBackgroundImage:[UIImage image:@"switch_camera"] forState:UIControlStateNormal];
    _cameraTypeBtn.center = CGPointMake(self.view.width - 50, 60);
    [_cameraTypeBtn addTarget:self action:@selector(cameraTypeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_cameraTypeBtn];
}

// 加载相机的下端的按钮
- (void)loadDownButtons {
    self.cancelBtn    = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelBtn.frame  = CGRectMake(0, 0, 80, 30);
    _cancelBtn.center = CGPointMake(40, self.view.height - 60);
    [_cancelBtn setTitle:HHH_Text(@"退出") forState:UIControlStateNormal];
    _cancelBtn.titleLabel.font = DEFAULT_FONTKhmerSangamMN(17);
    [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelBtn];
    
    self.takePictureBtn    = [UIButton buttonWithType:UIButtonTypeCustom];
    _takePictureBtn.frame  = CGRectMake(0, 0, 60, 60);
    _takePictureBtn.center = CGPointMake(self.view.center.x, self.view.height - 63);
    [_takePictureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_takePictureBtn addTarget:self action:@selector(takeImageClick:) forControlEvents:UIControlEventTouchUpInside];
    [_takePictureBtn setBackgroundImage:[UIImage image:@"takePicture"] forState:UIControlStateNormal];
    [self.view addSubview:_takePictureBtn];
    
    self.takedImage    = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.width/6, self.view.width/6)];
    _takedImage.center = CGPointMake(self.view.width - 40, self.view.height - 60);
    [_takedImage setBackgroundImage:[UIImage image:@"defaultImage.png"] forState:UIControlStateNormal];
    [_takedImage addTarget:self action:@selector(takedImageClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_takedImage];
    //
    self.testButton    = [UIButton buttonWithType:UIButtonTypeCustom];
    _testButton.frame  = CGRectMake(0, 0, 80, 30);
    _testButton.center = CGPointMake(40, self.view.height - 120);
    [_testButton setTitle:@"开启拍照" forState:UIControlStateNormal];
    _testButton.titleLabel.font = DEFAULT_FONTKhmerSangamMN(17);
    [_testButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_testButton addTarget:self action:@selector(testButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.testButton2    = [UIButton buttonWithType:UIButtonTypeCustom];
    _testButton2.frame  = CGRectMake(0, 0, 80, 30);
    _testButton2.center = CGPointMake(40 + 120, self.view.height - 120);
    [_testButton2 setTitle:@"关闭拍照" forState:UIControlStateNormal];
    _testButton2.titleLabel.font = DEFAULT_FONTKhmerSangamMN(17);
    [_testButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_testButton2 addTarget:self action:@selector(testButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}

////取消拍照返回
- (void)cancelBtnClick:(UIButton *)sender {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setPhotoControl) object:nil];
    [KK_BLESend sendControlTakePhotoState:NO WithUpdateBlock:^(id object, KKBLEAcceptType type) {
    }];
    [self.navigationController popViewControllerAnimated:YES];
}

/////拍照
- (void)takeImageClick:(UIButton *)sender {
    [self bltControlTakePhoto];
}

//拍照页面，切换前后摄像头按钮按钮
- (void)cameraTypeBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    [_captureManager switchCamera:sender.selected];
}

//拍照页面，闪光灯按钮
- (void)flashBtnClick:(UIButton *)sender {
    [_captureManager switchFlashMode:sender];
}

- (void)createGroupSelf {
    __block NSString *urlSting;
    
    self.imageArray = [[NSMutableArray alloc] init];
    ALAssetsLibrary                              *assetsLibrary = [[ALAssetsLibrary alloc] init];
    ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group) {
            // _albumName =[group valueForProperty:ALAssetsGroupPropertyName];  ///获取相册的名称
            //if ([_albumName isEqualToString:@"Camera Roll"] || [_albumName isEqualToString:AJ_NSLocalizedString(@"相机胶卷", nil)]) {
            
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if (result) {
                    //                        CGImageRef ratioThum = [result aspectRatioThumbnail];
                    //                        UIImage *rti = [UIImage imageWithCGImage:ratioThum];
                    urlSting = [[[result defaultRepresentation] url] description];
                    [_imageArray addObject:urlSting];
                }
            }];
            //}
        }
        
        
        if (_imageArray.count != 0) {
            NSURL *url = [NSURL URLWithString:_imageArray.lastObject];
            [assetsLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                [_takedImage setBackgroundImage:[UIImage imageWithCGImage:[asset defaultRepresentation].fullScreenImage] forState:UIControlStateNormal];
            } failureBlock:^(NSError *error) {
            }];
        }
    };
    
    
    //创建相簿
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:listGroupBlock failureBlock:nil];
}

//保存照片至本机
- (void)saveImageToPhotoAlbum:(UIImage *)image {
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error != NULL) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"错误!") message:SN_Text(@"保存失败") delegate:self cancelButtonTitle:SN_Text(@"确定") otherButtonTitles:nil, nil];
        [alert show];
    } else {
        _isEnable = YES;
        NSLog(@"保存成功");
    }
}

/**
 *  zhangj
 */
- (void)takedImageClick {
    [self createGroupSelf];  ///先去读取系统相册里的照片
    //[self performSelector:@selector(getImageViewShow) withObject:nil afterDelay:0.5];
}

- (void)getImageViewShow {
    ShowImagesController *show = [[ShowImagesController alloc] init];
    
    show.imagesArray = _imageArray;
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    path           = [path stringByAppendingPathComponent:@"album"];
    show.albumPath = path;
    if (_imageArray.count == 0) {
        return;
    }
    [self presentViewController:show animated:YES completion:^{
    }];
}

- (void)testButtonClick:(UIButton *)sender {
    if (sender == _testButton) {
        SHOWMBProgressHUD(@"开启照相", nil, nil, NO, 1.0);
    } else {
        SHOWMBProgressHUD(@"关闭照相", nil, nil, NO, 1.0);
    }
}

#pragma mark ---------------------对焦--------------------------
#if SWITCH_SHOW_FOCUSVIEW_UNTIL_FOCUS_DONE
//监听对焦是否完成了
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:ADJUSTINT_FOCUS]) {
        BOOL isAdjustingFocus = [[change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1] ];
        //        SCDLog(@"Is adjusting focus? %@", isAdjustingFocus ? @"YES" : @"NO" );
        //        SCDLog(@"Change dictionary: %@", change);
        if (!isAdjustingFocus) {
            alphaTimes = -1;
        }
    }
}

- (void)showFocusInPoint:(CGPoint)touchPoint {
    [UIView animateWithDuration:0.1f delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        int alphaNum = (alphaTimes % 2 == 0 ? HIGH_ALPHA : LOW_ALPHA);
        self.focusImageView.alpha = alphaNum;
        alphaTimes++;
    } completion:^(BOOL finished) {
        if (alphaTimes != -1) {
            [self showFocusInPoint:currTouchPoint];
        } else {
            self.focusImageView.alpha = 0.0f;
        }
    }];
}

#endif

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //    [super touchesBegan:touches withEvent:event];
    
    alphaTimes = -1;
    
    UITouch *touch = [touches anyObject];
    currTouchPoint = [touch locationInView:self.view];
    
    if (CGRectContainsPoint(_captureManager.previewLayer.bounds, currTouchPoint) == NO) {
        return;
    }
    
    [_captureManager focusInPoint:currTouchPoint];
    
    //对焦框
    [_focusImageView setCenter:currTouchPoint];
    _focusImageView.transform = CGAffineTransformMakeScale(2.0, 2.0);
    
#if SWITCH_SHOW_FOCUSVIEW_UNTIL_FOCUS_DONE
    [UIView animateWithDuration:0.1f animations:^{
        _focusImageView.alpha = HIGH_ALPHA;
        _focusImageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
        [self showFocusInPoint:currTouchPoint];
    }];
#else
    [UIView animateWithDuration:0.3f delay:0.f options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _focusImageView.alpha = 1.f;
        _focusImageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5f delay:0.5f options:UIViewAnimationOptionAllowUserInteraction animations:^{
            _focusImageView.alpha = 0.f;
        } completion:nil];
    }];
#endif
}

@end

